<?php
/**
 * Created by JetBrains PhpStorm.
 * User: zhouyang
 * Date: 13-7-15
 * Time: 下午4:31
 * To change this template use File | Settings | File Templates.
 */
class SourcesDB  extends DBReader{

    //根据source_id 获取 source 信息
    public function get($source_id){

        $sql = 'select source_id, title, site_address from sources where source_id = :source_id';

        return $this->db()->getRow($sql,array('source_id'=>$source_id));
    }

    //获取来源信息列表<带分页>
    public function getSourceList($curr_page,$per_page,$filter = array()){
        $where = ' 1=1 ';
        $bindarr = array();

        if(isset($filter['title'])){
            $where .= ' and title like :title';
            $bindarr['title'] = '%'.$filter['title'].'%';
        }

        $ret = $this->pager($curr_page, $per_page)
            ->ct('select count(source_id) from sources where '.$where,$bindarr)
            ->rs('select source_id, title, site_address from sources where '.$where.' order by source_id desc', $bindarr);
        return $ret;
    }

    //获取所有来源信息
    public function getSources($filter = array(),$flag = false){
        $where = ' 1=1 ';
        $bindarr = array();

        if(isset($filter['title'])){
            $where .= ' and title like :title';
            $bindarr['title'] = '%'.$filter['title'].'%';
        }

        $sql = 'select source_id, title, site_address from sources where '. $where .' order by source_id desc';

        $ret = $this->db()->getAll($sql,$bindarr);

        if($flag == false){
            return $ret;
        }else{
            $new_ret = array();

            foreach((array)$ret as $k=>$v){
                $new_ret[$v['source_id']] = $v['title'];
            }

            return $new_ret;
        }
    }

    //添加来源信息
    public function addSource($title, $site_address){

        $sql = "insert into sources(title,site_address) values(:title,:site_address)";

        $bindarr = array(
            'title'=>$title,
            'site_address'=>$site_address,
        );
        $this->db()->execute($sql,$bindarr);
        return $this->db()->lastInsertId();
    }

    //删除来源信息
    public function delSource($source_id){

        $sql = "delete from sources where source_id = :source_id";

        $bindarr = array(
            'source_id'=>$source_id,
        );
        $rs = $this->db()->execute($sql,$bindarr);

        return $rs->rowCount();
    }

    //更新来源信息
    public function updateSource($id,$title,$site_address){

        $bindarr = array(
            'source_id'=>$id,
            'title'=>$title,
            'site_address'=>$site_address,
        );
        $sql = "update sources set title = :title, site_address = :site_address where source_id = :source_id";
        $rs = $this->db()->execute($sql,$bindarr);
        return $rs->rowCount();
    }
}